# -- coding:UTF-8 --

import utils.env_conf

from flask import Flask, request, render_template, jsonify
from flask_cors import *
import json
import datetime,os,re

from utils.OpenAiService import getParam, getFun, getScene,getContrast
from utils.StaticObj import SYSTEM_PROMPT, ORG_CONF, FUNCTIONS, ORG_ID, SRC_CL, \
    create_data_file, save_to_file, FUN_DICT_BAK, SELECT, Echart_Not, BANHEZHAN_PROMPT, BANHEZHAN_CL,\
    SCENE_KEY_VALUE,SCENE_PROMPT,SCENE_KEY, SCENE_VALUE, SCENE,SELECT_TWO,CONFUNCTIONS,CON_DICT,\
    CON_SYSTEM_PROMPT,CON_TWO_SYSTEM_PROMPT,CON_TWO_MAX_SYSTEM_PROMPT
from utils.JsonResult import JsonResult

application = Flask(__name__)
CORS(application, supports_credentials=True)

@application.route('/')
def index():
    return render_template('index.html')

@application.route('/his')
def his():
    return render_template('history.html')

@application.route('/chat', methods=['GET'])
def chat():
    un = request.args.get('un')
    permission = request.args.get('p') if request.args.get('p') else 'user1'
    query = request.args.get('query')
    print(un, permission, query)
    now = datetime.datetime.now()
    today = now.strftime("%Y-%m-%d")
    systemPrompt = SYSTEM_PROMPT.format(today,SRC_CL, ORG_CONF[permission])
    paramsMsg = getParam(un, query, FUNCTIONS, sysStr=systemPrompt)

    resData = {
        'answer': vars(paramsMsg),
        'data': [],
        'funname': '',
        'funargs': {}
    }
    if paramsMsg.function_call:
        functionName = paramsMsg.function_call['name']
        print(functionName,paramsMsg.function_call['arguments'])
        functionArgs = json.loads(paramsMsg.function_call['arguments'])
        data = FUN_DICT_BAK[functionName](functionArgs,ORG_ID[permission])
        if functionName =="inventoryStatic":
            for key, value in data.items():
                systemPrompt = SYSTEM_PROMPT.format(today, ','.join(value['materials']), ORG_CONF[permission])
        answer = getFun(un, data, functionName, sysStr=systemPrompt)
        print(answer.content)
        resData['answer'] = vars(answer)
        resData['data'] = data
        resData['funname'] = functionName
        resData['funargs'] = functionArgs
    return jsonify(vars(JsonResult(200, 'ok', resData)))

@application.route('/chatbak', methods=['GET'])
def chatbak():
    un = request.args.get('un')
    permission = request.args.get('p') if request.args.get('p') else 'user1'
    query = request.args.get('query')
    scene = request.args.get('scene')
    print(un, permission, query, scene)
    now = datetime.datetime.now()
    today = now.strftime("%Y-%m-%d")
    print(today)
    if scene == 'mix':
        systemPrompt = BANHEZHAN_PROMPT.format(today,BANHEZHAN_CL,ORG_CONF[permission])
    else:
        systemPrompt = SYSTEM_PROMPT.format(today,SRC_CL, ORG_CONF[permission])
    paramsMsg = getParam(un, query, FUNCTIONS, sysStr=systemPrompt)

    resData = {
        'answer': vars(paramsMsg),
        'data': [],
        'funname': '',
        'funargs': {}
    }
    if paramsMsg.function_call:
        functionName = paramsMsg.function_call['name']
        print(paramsMsg.function_call['arguments'])
        functionArgs = json.loads(paramsMsg.function_call['arguments'])
        if functionName not in SELECT[scene]:
            resData['answer'] = '您问的问题不符合当前情景'
            resData['data'] = ''
            resData['funname'] = functionName
            resData['funargs'] = functionArgs
            return jsonify(vars(JsonResult(200, 'ok', resData)))
        else:
            data = SELECT[scene][functionName](functionArgs,ORG_ID[permission])
            if functionName in Echart_Not:
                resData['answer'] = data
                # resData['data'] = data
                resData['isHasChart'] = False
                resData['funname'] = functionName
                resData['funargs'] = functionArgs
            else:
            #     for key, value in data.items():
            #         systemPrompt = SYSTEM_PROMPT.format(today, ','.join(value['materials']), ORG_CONF[permission])
            # answer = getFun(un, data, functionName, sysStr=systemPrompt)
            # print(answer.content)
                resData['answer'] = data
                # resData['data'] = data
                resData['isHasChart'] = True
                resData['funname'] = functionName
                resData['funargs'] = functionArgs
    return jsonify(vars(JsonResult(200, 'ok', resData)))

@application.route('/chatbaktwo', methods=['GET'])
def chatbakTWO():
    un = request.args.get('un')
    permission = request.args.get('p') if request.args.get('p') else 'user1'
    query = request.args.get('query')
    scene = request.args.get('scene')
    print(un, permission, query, scene)
    now = datetime.datetime.now()
    today = now.strftime("%Y-%m-%d")
    print(today)
    if scene == 'mix':
        systemPrompt = BANHEZHAN_PROMPT.format(today,BANHEZHAN_CL,ORG_CONF[permission])
    else:
        systemPrompt = SYSTEM_PROMPT.format(today,SRC_CL, ORG_CONF[permission])
    paramsMsg = getParam(un, query, FUNCTIONS, sysStr=systemPrompt)

    resData = {
        'answer': vars(paramsMsg),
        'data': [],
        'funname': '',
        'funargs': {}
    }
    if paramsMsg.function_call:
        functionName = paramsMsg.function_call['name']
        print(paramsMsg.function_call['arguments'])
        functionArgs = json.loads(paramsMsg.function_call['arguments'])
        if functionName not in SELECT_TWO[scene]:
            resData['answer'] = '您问的问题不符合当前情景'
            resData['data'] = ''
            resData['funname'] = functionName
            resData['funargs'] = functionArgs
            return jsonify(vars(JsonResult(200, 'ok', resData)))
        else:
            data,markdown,title = SELECT_TWO[scene][functionName](functionArgs,ORG_ID[permission])
            if functionName in Echart_Not:
                resData['answer'] = markdown
                resData['data'] = data
                resData['title'] = title
                resData['isHasChart'] = False
                resData['funname'] = functionName
                resData['funargs'] = functionArgs
            else:
            #     for key, value in data.items():
            #         systemPrompt = SYSTEM_PROMPT.format(today, ','.join(value['materials']), ORG_CONF[permission])
            # answer = getFun(un, data, functionName, sysStr=systemPrompt)
            # print(answer.content)
                resData['answer'] = markdown
                resData['data'] = data
                resData['title'] = title
                resData['isHasChart'] = True
                resData['funname'] = functionName
                resData['funargs'] = functionArgs
    return jsonify(vars(JsonResult(200, 'ok', resData)))


@application.route('/charts', methods=['POST'])
def charts():
    data = request.get_data()
    dataJson = json.loads(data)

    # 提取拌合站名称和材料列表
    stations = list(dataJson.keys())
    materials = dataJson[stations[0]]['materials']  # Assuming all stations have the same materials
    # 构建 ECharts 格式的数据
    echarts_data = [['product'] + materials]
    for station in stations:
        weights = dataJson[station]['weights']
        echarts_data.append([station] + weights)
    second_condition = True
    try:
        scene = dataJson[stations[0]]['scene']
        if scene[0] == '2':
            for stations in stations:
                materials = dataJson[stations]['materials']
                shijiweights = dataJson[stations]['shijizhi1']
                lilunweights = dataJson[stations]['lilunzhi1']
                echarts_data1 = [[x, y, z] for x, y, z in zip(materials, shijiweights, lilunweights)]
                chart_options = {
                    'legend': {},
                    'tooltip': {'trigger': 'axis','axisPointer': {'type': 'cross'}},
                    'dataset': {
                        'dimensions': ['product', '实际用料', '理论用料'],
                        'source': echarts_data1
                    },
                    'xAxis': { 'type': 'category' },
                    'yAxis': {},
                    'series': [{ 'type': 'bar' ,'barGap': '0%',
                                'barCategoryGap': '15%'},
                               { 'type': 'bar',	'barGap': '0%',
                                'barCategoryGap': '15%'}]
                }
                second_condition = False
    except (KeyError, IndexError):
        pass
    if second_condition:
        # 构建 ECharts 配置
        chart_options = {
            'legend': {
                "type": "scroll",
                "orient":'horizontal'
            },
            'tooltip': {},
            'dataset': {
                'source': echarts_data
            },
            'xAxis': {'type': 'category'},
            'yAxis': {},
            'series': [{'type': 'bar','barGap': '0%',
                        'barCategoryGap': '15%'}] * len(materials)
        }
    print(chart_options)
    return jsonify(vars(JsonResult(200, 'ok', chart_options)))

@application.route('/savet', methods=['POST'])
def save_to_txt():
    try:
        data = request.json
        content = data.get("content", "")
        charts = data.get("charts", "")
        query = data.get("query", "")

        entry = {"content": content, "charts": charts}
        qa_entry = f"问：{query}\n答：{json.dumps(entry,ensure_ascii=False)}"

        create_data_file()  # 创建数据文件
        if save_to_file(qa_entry):
            return jsonify({"message": "Data saved successfully."})
        else:
            return jsonify({"message": "Error saving data."}), 500

    except Exception as e:
        print(f"Error processing request: {e}")
        return jsonify({"message": "An error occurred."}), 500


@application.route('/hisList', methods=['GET'])
def his_list():
    page = int(request.args.get('pgNo'))
    # size = int(request.args.get('size'))
    size = 10
    file = open(os.environ.get('DATA_FOLDER'), 'r')
    cons = file.readlines()
    st = size*(page-1)
    his = []
    qa = {}
    flag = 1
    for i in range(cons.__len__()):
        if cons[i].strip() != '':
            if flag == 1:
                qa.setdefault('q', cons[i].replace('\\n', '').strip()[2:])
                flag = 2
            else:
                qa.setdefault('a', cons[i].replace('\\n', '').strip()[2:])
        else:
            his.append(qa)
            qa = {}
            flag = 1
    if size+st > his.__len__():
        sums = his.__len__()
    else:
        sums = size*page
    resData = {
        'his': his[st:sums],
        'sum': his.__len__(),
    }
    return jsonify(vars(JsonResult(200, 'ok', resData)))

@application.route('/scene', methods=['GET'])
def scene():
    query = request.args.get('query')
    un = request.args.get('un')
    permission = 'user1'
    now = datetime.datetime.now()
    today = now.strftime("%Y-%m-%d")
    systemPrompt = SYSTEM_PROMPT.format(today, SRC_CL, ORG_CONF[permission])
    paramsMsg = getParam(un, query, FUNCTIONS, sysStr=systemPrompt)
    print(paramsMsg.function_call['name'])
    # systemPrompt = SCENE_PROMPT
    # paramsMsg = getScene(un,query, sysStr=systemPrompt)
    scenes = ''
    for key, val in SCENE.items():
        for i in range(val.__len__()):
            # print(val[i],paramsMsg.function_call['name'])
            if re.search(val[i],paramsMsg.function_call['name']):
                scenes = key
                break
    return jsonify(vars(JsonResult(200, 'ok', scenes)))

@application.route('/contrast', methods=['GET'])
def contrast():
    un = request.args.get('un')
    permission = 'user1'
    query = request.args.get('query')
    print(un, permission, query)
    now = datetime.datetime.now()
    today = now.strftime("%Y-%m-%d")
    systemPrompt = CON_SYSTEM_PROMPT.format(today,SRC_CL, ORG_CONF[permission])
    paramsMsg = getParam(un, query, CONFUNCTIONS, sysStr=systemPrompt)

    resData = {
        'answer': vars(paramsMsg),
        'data': [],
        'funname': '',
        'funargs': {}
    }
    if paramsMsg.function_call:
        functionName = paramsMsg.function_call['name']
        print(functionName,paramsMsg.function_call['arguments'])
        functionArgs = json.loads(paramsMsg.function_call['arguments'])
        data,mes = CON_DICT[functionName](functionArgs,ORG_ID[permission])
        print(data)
        # if functionName =="inventoryStatic":
        #     for key, value in data.items():
        #         systemPrompt = SYSTEM_PROMPT.format(today, ','.join(value['materials']), ORG_CONF[permission])
        answer = getFun(un, data, functionName, sysStr=systemPrompt)
        print(mes)
        if functionName == 'shengchanrw_ovStatic':
            systemPrompt = CON_TWO_MAX_SYSTEM_PROMPT.format(today, ORG_CONF[permission])
        else:
            systemPrompt = CON_TWO_SYSTEM_PROMPT.format(today, SRC_CL, ORG_CONF[permission])
        conanswer,ec = getContrast(un+'contrast', mes, functionName, sysStr=systemPrompt)
        print(answer.content)
        print(conanswer.content)
        print(ec)
        resData['answer'] = vars(answer)
        resData['contrast'] = vars(conanswer)
        resData['ec'] = ec
        resData['data'] = data
        resData['funname'] = functionName
        resData['funargs'] = functionArgs
    return jsonify(vars(JsonResult(200, 'ok', resData)))

if __name__ == '__main__':
    application.run(host='0.0.0.0', port=4000)
